package com.sesame.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.kevinsawicki.http.HttpRequest;
import com.sesame.entity.User;
import com.sesame.user.dao.UserMapper;
import com.sesame.user.service.UserService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;

@CommonsLog
@Service
@CacheConfig(cacheNames = "web-user")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    @Cacheable(key = "#id")
    public User detailById(String id) {
        log.info(">>>>>>进入 service detail id:"+id);
        return this.getById(id);
    }

    @CachePut(key = "#id")
    @Override
    public User update(String id, String name) {
//        this.update(new LambdaUpdateWrapper<User>()
//                .eq(User::getId, id)
//                .set(User::getName, name)
//                .set(User::getModifyTime, new Date())
//        );
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setModifyTime(new Date());

        this.updateById(user);

        return user;
    }

    @Cacheable(key = "#id")
    @Override
    public User add(String name) {
        User user = new User();
        user.setName(name);
        user.setModifyTime(new Date());
        this.save(user);

        return user;
    }

    @CacheEvict(key ="#id" )
    @Override
    public void del(String id) {
//        this.removeById(id);
    }

    @CachePut(key = "#id")
    @Override
    public User updateCacheDetail(String id) {
        log.info(">>>>>>进入 service updateCacheDetail id:"+id);

        new Thread(()->{
            try {
                // 清理nginx缓存
                String url = "http://www.userweb.com/purge/user/detail?id="+id;
                System.out.println(url);
               String res =  HttpRequest.get(url).body();
                System.out.println("清理nginx请求结果");
                System.out.println(res);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        User user = this.getById(id);;

        return user;
    }

}
